/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lintulaskenta.tipuapiValidointi;

import java.net.URISyntaxException;
import org.apache.http.client.methods.HttpGet;
import lintulaskenta.tipuapiValidointi.Document.Node;
import lintulaskenta.tipuapiValidointi.Selection.SelectionOptionImple;
/**
 *
 * @author jukkapajunen
 */
public class TipuAPIClient implements TipuAPIClientInterface{

    private final HttpClientService httpclient;
    private final String uri;

    public TipuAPIClient(String uri, String username, String password) throws URISyntaxException {
        this.uri = uri;
        this.httpclient = new HttpClientService(uri, username, password);
    }
    @Override
	public void close() {
		httpclient.close();
	}

	@Override
	public TipuApiResource get(String resourcename) throws Exception {
		Document document = getAsDocument(resourcename);
		TipuApiResource resource = new TipuApiResource();
		for (Node node : document.getRootNode().getChildNodes()) {
			resource.add(node);
		}
		return resource;
	}
        @Override
	public Document getAsDocument(String ressourcename) throws Exception {
		HttpGet request = new HttpGet(uri + "/" + ressourcename);
		Document document = httpclient.contentAsDocument(request);
		return document;
	}

	@Override
	public Document getAsDocument(String ressourcename, String id) throws Exception {
		HttpGet request = new HttpGet(uri + "/" + ressourcename + "/" + id);
		Document document = httpclient.contentAsDocument(request);
		return document;
	}
        @Override
	public Selection getAsSelection(String ressourcename) throws Exception {
		return getAsSelection(ressourcename, Integer.MAX_VALUE);
	}
	
	@Override
	public Selection getAsSelection(String ressourcename, int countOfFields) throws Exception {
		Document document = getAsDocument(ressourcename);
		Selection selection = new Selection(ressourcename);
		for (Node ressource : document.getRootNode()) {
			String id = ressource.getNode("id").getContents();
			StringBuilder desc = new StringBuilder();
			int i = 0;
			for (Node ressourceChild : ressource) {
				if (i++ > countOfFields) break;
				if (ressourceChild.getName().equals("id")) continue;
				String contents = ressourceChild.getContents();
				if (contents == null) continue;
				desc.append(contents).append(" ");
			}
			removeLastChar(desc);
			selection.addOption(new SelectionOptionImple(id, desc.toString()));
		}
		return selection;
	}
        public static void removeLastChar(StringBuilder query) {
		if (query.length() < 1) return;
		query.deleteCharAt(query.length()-1);
	}
}
